﻿using AutoMapper;
using B.S.DataBasic.Domain.GoodInfra;
using B.S.DataBasic.Domain.RBAC;
using B.S.DataBasic.ErrorCode;
using B.S.DataBasic.Infrastructure.Implement;
using B.S.DataBasic.Read.API.Dtos;
using MediatR;

namespace B.S.DataBasic.Read.API.Application
{
    public class ShowCommandHandler : IRequestHandler<ShowCommand, APIResult<APIPaging<TranceDto>>>
    {
        private readonly IBaseRepository<Traceabilitable> traceRepository;
        private readonly IMapper mapper;
        public ShowCommandHandler(IBaseRepository<Traceabilitable> traceRepository, IMapper mapper)
        {
            this.traceRepository = traceRepository;
            this.mapper = mapper;
        }
        public Task<APIResult<APIPaging<TranceDto>>> Handle(ShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<TranceDto>> result = new APIResult<APIPaging<TranceDto>>();
            result.Code = EnumCode.查询成功;
            result.Message = EnumCode.查询成功.ToString();

            var list = from a in traceRepository.GetAll()
                       where !a.IsDeleted
                       select new TranceDto
                       {
                           Coverimage = a.Coverimage,
                           GoodsId = a.GoodsId,
                           IsDeleted = a.IsDeleted,
                           Productionbatches = a.Productionbatches,
                           ProductionCompany = a.ProductionCompany,
                           Productionlicense = a.Productionlicense,
                           ShelflifeDay = a.ShelflifeDay,

                       };

            int recordCount = list.Count();
            int pageCount = (int)Math.Ceiling(recordCount * 1.0 / request.PageSize);
            list = list.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize);

            APIPaging<TranceDto> paging = new APIPaging<TranceDto>();
            paging.RecordCount = recordCount;
            paging.PageCount = pageCount;
            paging.list = list.ToList();

            result.Data = paging;

            return Task.FromResult(result);
        }
    }
}
